﻿using _9jCardRegisterCollection.Models;
using AntdUI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using CardRegisterCollection.Model;
using Message = AntdUI.Message;
using Unit = CardRegisterCollection.BLL.Unit;

namespace _9jCardRegisterCollection.Views
{
    public partial class UnitManagementPage : UserControl
    {
        private AntdUI.Window window;


        public UnitManagementPage(AntdUI.Window _window)
        {
            window = _window;
            InitializeComponent();
            //初始化表格列头
            InitTableColumns();
            InitData();
            //BindEventHandler();
        }


        private readonly Unit _unitBll = new Unit();
        private readonly CardRegisterCollection.BLL.User userBll = new CardRegisterCollection.BLL.User();

        AntList<UnitExpand> dataList;

        private void InitTableColumns()
        {
            tabUnits.Columns = new ColumnCollection() {
                new Column("Name", "单位名称", ColumnAlign.Center){         KeyTree = "Depts"},
                new Column("CreatedBy", "创建人",ColumnAlign.Center),
                new Column("CreatedAt", "创建时间"),
                new Column("CellLinks", "操作", ColumnAlign.Center)
                {
                    Fixed = true,//冻结列
                },
            };
        }

        private void InitData()
        {
            var unitList = new List<UnitExpand>();
            var strWhere = "";
            if (txtKeyword.Text.Trim().Length > 0)
            {
                strWhere += " Name like '%" + txtKeyword.Text.Trim().ToString() + "%' ";
            }

            var ds = _unitBll.GetList(strWhere);
            if (ds != null && ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    unitList.Add(new UnitExpand
                    {
                        ID = row["ID"]?.ToString(),
                        ParentId = row["ParentId"]?.ToString(),
                        Name = row["Name"].ToString(),
                        Type = row.IsNull("Type") ? 0 : Convert.ToInt32(row["Type"]),
                        CreatedBy = row.IsNull("CreatedBy") ? string.Empty : row["CreatedBy"].ToString(),
                        CreatedAt = row.IsNull("CreatedAt") ? (DateTime?)null : Convert.ToDateTime(row["CreatedAt"]),
                        DeleteFlag = Convert.ToBoolean(row["DeleteFlag"]),
                    });
                }
            }

            // 获取所有单位
            var units = unitList.Where(x => x.Type == 0).ToList();
            var deptList = _unitBll.GetModelList(" [type] = 1");
            // 将部门绑定到所属单位
            foreach (var unit in units)
            {
                unit.Depts = deptList.Where(_ => _.ParentId.Equals(unit.ID)).Select(_ => new UnitExpand()
                {
                    ID = _.ID,
                    ParentId = _.ParentId,
                    Name = _.Name,
                    Type = _.Type,
                    CreatedBy = _.CreatedBy,
                    DeleteFlag = _.DeleteFlag,
                }).ToArray();
                foreach (var dept in unit.Depts)
                {
                    dept.CellLinks = new CellLink[]  //用于绑定表格控件的编辑和删除操作
                    {
                        new CellButton("Edit", "编辑", TTypeMini.Primary),
                        new CellButton("Del", "删除", TTypeMini.Error),

                    };
                }
            }

            dataList = new AntList<UnitExpand>(units);
            tabUnits.Binding(dataList);
        }


        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void butCreate_Click(object sender, EventArgs e)
        {
            var modelUnit = new CardRegisterCollection.Model.Unit()
            {
                ID = Guid.NewGuid().ToString(),
                ParentId = "0",
                Type = 0,
                CreatedAt = DateTime.Now,
                CreatedBy = CurrentLoginInfo.UserInfo.UserName
            };

            var form = new UnitEdit(window, modelUnit) { };
            Modal.open(new AntdUI.Modal.Config(window, "创建单位", form, TType.None)
            {
                BtnHeight = 0,
            }); ;
            if (form.Submit)
            {
                _unitBll.Add(modelUnit);
                InitData();
            }
        }

        private void tabUnits_CellButtonClick(object sender, TableButtonEventArgs e)
        {
            var data = (UnitExpand)e.Record;
            if (data == null) return;



            var id = e.Btn.Id;
            switch (id)
            {
                case "CreateDept":
                    {
                        var modelUnit = new CardRegisterCollection.Model.Unit()
                        {
                            ID = Guid.NewGuid().ToString(),
                            ParentId = data.ID,
                            Type = 1,
                            CreatedAt = DateTime.Now,
                            CreatedBy = CurrentLoginInfo.UserInfo.UserName
                        };
                        var form = new UnitEdit(window, modelUnit);
                        Modal.open(new AntdUI.Modal.Config(window, "创建部门", form, TType.None)
                        {
                            BtnHeight = 0,
                        }); ;
                        if (form.Submit)
                        {
                            _unitBll.Add(modelUnit);
                            InitData();
                        }
                    }
                    break;
                case "Edit":
                    {
                        var form = new UnitEdit(window, data);
                        Modal.open(new AntdUI.Modal.Config(window, "修改", form, TType.None)
                        {
                            BtnHeight = 0,
                        }); ;
                        if (form.Submit)
                        {
                            _unitBll.Update(data);
                            InitData();
                        }
                    }
                    break;
                case "Del":
                    {
                        DelById(data);
                    }
                    break;
            }
        }


        private void DelById(UnitExpand unit)
        {
            var userExistRlt = userBll.Exists($" and ([UnitId] = '{unit.ID}' or [DeptId] = '{unit.ID}')");
            if (userExistRlt)
            {
                Message.warn(window, "单位/部门下存在用户，无法删除");
                return;
            }

            if (unit.Type == 0)
            {
                var deptExistRlt = _unitBll.Exists($" and [ParentId] = '{unit.ID}' ");
                if (deptExistRlt)
                {
                    Message.warn(window, "单位下存在部门，请先删除部门");
                    return;
                }
            }

            _unitBll.Delete(unit.ID);
            InitData();
        }

        private void butSearch_Click(object sender, EventArgs e)
        {
            InitData();
        }
    }
}
